<template>
  <div class="app-container">
    <!--编写ElementUI组件-->
    <el-button type="success" @click="addCart">新增</el-button>
    <el-popconfirm title="确定删除商品吗？" @onConfirm="deleteCart">
      <el-button type="danger" style="margin-left:10px" slot="reference">删除</el-button>
    </el-popconfirm>
    <br/>
    <!--表格-->
    <el-table
      ref="multipleTable"
      :data="products"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="checked">
      <el-table-column type="selection" width="50"></el-table-column>
      <el-table-column label="序号" type="index" width="50" align="center"></el-table-column>
      <el-table-column  label="商品图片" align="center" width="150" >
        <template slot-scope="scope">
          <el-image style="width:150px;height:150px" :src="imgUrl+scope.row.pimage"/>
        </template>
      </el-table-column>
      <el-table-column prop="productName" label="商品名称" align="center" width="150"></el-table-column>
      <el-table-column prop="productPrice" label="商品价格" align="center" width="150"></el-table-column>
      <el-table-column prop="productKind" label="商品类别" align="center" ></el-table-column>
      <el-table-column prop="productNum" label="库存数量" align="center" ></el-table-column>
      <el-table-column prop="pState.productStateName" label="商品状态" align="center" ></el-table-column>
      <el-table-column label="操作" min-width="100" align="center">
        <template slot-scope="scope" v-if="scope.row.productState===1">
          <el-button  size="mini" type="primary" @click="getProduct(scope.row.productId)">加入订单</el-button>
        </template>
      </el-table-column>
    </el-table>
    <br/>
    <!--分页栏-->
    <el-row>
      <el-col :span="20" align="center">
        <el-pagination background layout="prev, pager, next" :current-page="currentPage" :hide-on-single-page="hidePage" :page-size="pageSize" :total="total" @current-change="page"></el-pagination>
      </el-col>
    </el-row>
    <!--更新弹窗-->
    <el-dialog title="新增订单" status-icon :visible.sync="orderDialogVisible" >
      <el-form :model="orderForm" ref="orderForm" :rules="rules">
        <!--<el-row>-->
          <!--<el-col :span="12">-->
            <!--<el-form-item label="购买人" >-->
              <!--<el-input  v-model="orderForm.user.userName"  autocomplete="off" :disabled="true"></el-input>-->
            <!--</el-form-item>-->
          <!--</el-col>-->
        <!--</el-row>-->
        <!--<el-row :gutter="60">-->
          <!--<el-col :span="12">-->
            <!--<el-form-item label="商品名称" >-->
              <!--<el-input v-model="orderForm.product.productName"   :disabled="true" autocomplete="off"></el-input>-->
            <!--</el-form-item>-->
          <!--</el-col>-->
        <!--</el-row>-->
        <el-row :gutter="60">
          <el-col :span="12">
            <el-form-item label="购买数量" prop="orderProductNum" >
              <el-input v-model.number="orderForm.orderProductNum" autocomplete="off" clearable></el-input>
              库存数:<span>{{orderForm.product.productNum}}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="60">
          <el-col :span="12">
            <el-form-item label="收货地址" prop="orderAddress" >
              <el-input v-model="orderForm.orderAddress" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!--<el-row :gutter="60">-->
          <!--<el-col :span="12">-->
            <!--<el-form-item label="商品价格" >-->
              <!--<el-input v-model="orderForm.product.productPrice" autocomplete="off" :disabled="true"></el-input>-->
            <!--</el-form-item>-->
          <!--</el-col>-->
        <!--</el-row>-->
        <!--<el-row :gutter="60">-->
          <!--<el-col :span="12">-->
            <!--<el-form-item label="订单时间" >-->
              <!--<el-input v-model="orderForm.orderDate" autocomplete="off" :disabled="true"></el-input>-->
            <!--</el-form-item>-->
          <!--</el-col>-->
        <!--</el-row>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('orderForm')">取 消</el-button>
        <el-button type="primary" @click="addOrder">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import request from '@/utils/cbp-request.js'
  import Cookies from 'js-cookie'
  // 编写vue.js代码
  export default {
    data() {
      var checkNum = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('数量不能为空'));
        }
        setTimeout(() => {
          if (!Number.isInteger(value)) {
            callback(new Error('请输入数字值'));
          } else {
            if (value > this.orderForm.product.productNum) {
              callback(new Error('库存不足'));
            } else {
              callback();
            }
          }
        }, 1000);
      };
      return {
        imgUrl:'http://localhost:8088/cbp/static/work/Tomcat/localhost/ROOT/',
        deleteIds: [],
        currentPage: 1,
        pageSize: 5,
        total: 0,
        hidePage: true,
        products: [],
        orderDialogVisible: false,
        orderForm: {
          user: {
            userName: ''
          },
          product: {
            productName: '',
            productPrice: '',
            productNum: '',
          },
          orderUser: '',
          orderProduct: '',
          orderProductNum: '',
          orderPrice: '',
          orderAddress: '',
          orderDate: '',
          orderState: 4
        },
        rules: {
          orderProductNum: [
            {validator: checkNum, trigger: 'blur'}
          ],
          orderAddress:[
            { required: true, message: '请输入收货地址', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      page(pageNum){
        var userId = Cookies.get("user_id");
        request({
          url:'/product/pageCart/'+pageNum+"/"+5+"/"+userId,
          method:'get',
        }).then((resp) =>{
          this.products = resp.data.list;
          this.total = resp.data.total;
          this.currentPage = resp.data.pageNum;
        })
      },
      addCart(){
        this.$router.push('/product-maintain');
      },
      checked(selection){
        this.deleteIds = [];//还原数组数据
        for (let i = 0; i < selection.length; i++) {
          this.deleteIds.push(selection[i].productId);//项数组添加数据
        }
      },
      // 弹窗回显商品信息
      getProduct(productId) {
        //查询点击按钮所在行的商品
        request({
          url: '/product/'+productId,
          method: 'get',
        }).then((resp) => {
          if (resp.status === 2000) {
            var userId=Cookies.get("user_id");
            var userName=Cookies.get("user_name");
            this.orderForm.user.userName=userName;
            this.orderForm.orderProduct=resp.data.productId;
            this.orderForm.product.productName=resp.data.productName;
            this.orderForm.product.productNum=resp.data.productNum;
            this.orderForm.product.productPrice=resp.data.productPrice;
            this.orderForm.orderUser=userId;
            var date = new Date();
            this.orderForm.orderDate=date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
            this.orderDialogVisible=true;
            this.$message({
              message: resp.msg,
              type: 'success'
            });
          }
        })
      },
      addOrder(){
        this.$refs['orderForm'].validate((valid) => {
          if (valid) {
            request({
              url: '/order',
              method: 'post',
              data:this.orderForm
            }).then((resp) => {
              if (resp.status === 2000){
                this.$message({
                  message: resp.msg,
                  type: 'success'
                });
                this.orderDialogVisible=false;
                this.page(1);
              }
            });
          } else {
            return false;
          }
        });

      },
      resetForm(formName) {
        this.orderDialogVisible=false;
        this.$refs[formName].resetFields();
      },
      deleteCart(){
        //判断是否选中
        if(this.deleteIds.length > 0){
          //发送后端进行删除处理
          var userId = Cookies.get("user_id",userId);
          request({
            url: '/userProduct/'+userId,
            method: 'delete',
            data:this.deleteIds
          }).then((resp) => {
            if(resp.status === 2000){
              this.$message({
                message: resp.msg,
                type: 'success'
              });
              if (this.total%this.pageSize ==1){
                this.currentPage=this.currentPage-1;
              }
              this.page(this.currentPage)//刷新
            }
          }).catch((error) => {
          })
        }else{
          this.$message({
            message: '删除商品，需要至少勾选一项',
            type: 'warning'
          });
        }
      },
    },mounted() {
      this.page(1);
    }
  }
</script>

<style scoped>
  .app-container {
    position: relative;
    width: 100%;
    height: calc(100vh - 84px);
  }
</style>
